import "package:flutter/material.dart";
import "package:shared_preferences/shared_preferences.dart";

import "../../viewModels/WordBookViewModel.dart";
import "../../widgets/general/PartingLine.dart";

class SilentTest extends StatefulWidget {
  const SilentTest({super.key});

  @override
  State<SilentTest> createState() => _SilentTestState();
}

class _SilentTestState extends State<SilentTest> {
  List<Map<String, dynamic>> _words = [];
  List<Map<String, dynamic>> _currentList = [];
  int _currentIndex = 0;
  int _totalInputCount = 0;

  String _targetWord = "error";
  String _targetTranslation = "错误";
  String _example = "";
  String _exampleTranslation = "";
  String _typedWord = "";
  List<Color> _wordColors = [];

  late final TextEditingController _textEditingController;
  final WordBookViewModel _wordBookViewModel = WordBookViewModel();
  bool _showHiddenWord = false;
  bool _showNextButton = false;

  @override
  void initState() {
    _textEditingController = TextEditingController();
    _fetchWordList(); // 直接加载数据
    super.initState();
  }

  Future<void> _fetchWordList() async {
    final prefs = await SharedPreferences.getInstance();
    // String bookId = prefs.getString("selectBook") ?? "";
    // int count = prefs.getInt("reviewWordCount") ?? 10;

    List<Map<String, dynamic>> wordList = await _wordBookViewModel.getRandomReviewWordListByEvent(1);
    if (wordList.isEmpty) {
      _showNoWordsDialog();
      return;
    }

    setState(() {
      _words = wordList.map((e) => {...e, "correctCount": 0}).toList();
      _initCurrentList();
    });
  }

  // 其他方法保持不变...
  void _initCurrentList() {
    _currentList = List.from(_words);
    if (_currentList.isNotEmpty) {
      _updateDisplayWord();
    }
  }

  void _updateDisplayWord() {
    setState(() {
      _targetWord = _currentList[_currentIndex]["word"] ?? "error";
      _targetTranslation = _currentList[_currentIndex]["tran"] ?? "错误";
      _example = _currentList[_currentIndex]["example"] ?? "No example available";
      _exampleTranslation = _currentList[_currentIndex]["exampleTran"] ?? "本单词暂无例句";
      _wordColors = List.generate(_targetWord.length, (index) => Colors.grey);
      _showHiddenWord = false; // 初始化时不显示隐藏的单词
    });
  }

  void _updateTypedWord(String input) {
    setState(() {
      _typedWord = input;
    });

    // 输入完成后处理
    if (input.length == _targetWord.length) {
      bool allCorrect = true;

      // 检查拼写是否正确
      for (int i = 0; i < input.length; i++) {
        if (input[i] != _targetWord[i]) {
          allCorrect = false;
          break;
        }
      }

      // 更新颜色反馈
      setState(() {
        _wordColors = List.generate(_targetWord.length, (index) {
          if (input.length > index) {
            if (input[index] == _targetWord[index]) {
              return Colors.green;
            } else if (_targetWord.contains(input[index])) {
              return Colors.black;
            } else {
              return Theme.of(context).colorScheme.error;
            }
          } else {
            return Colors.grey;
          }
        });
        _showHiddenWord = true; // 输入完成后显示隐藏的单词
        _showNextButton = !allCorrect; // 只有在输入有误时显示“下一个单词”按钮
      });

      // 只有在输入正确时自动处理
      if (allCorrect) {
        Future.delayed(const Duration(milliseconds: 800), () {
          setState(() {
            _totalInputCount++; // 只有在输入正确时，总输入次数加1
            _currentList[_currentIndex]["correctCount"] += 1;

            // 删除原来的判断逻辑，直接切换到下一个单词
            _wordBookViewModel.saveOrUpdateReview(_currentList[_currentIndex]["word"]);
            _currentList.removeAt(_currentIndex);
            if (_currentList.isEmpty) {
              _showCompletionDialog();
              return;
            }
            _currentIndex = _currentIndex >= _currentList.length ? 0 : _currentIndex;
            _updateDisplayWord();
            _clearInput();
          });
        });
      }
    } else {
      // 即使还没输完单词，输入的单词在提示单词中，这个字母也变黑色
      setState(() {
        _wordColors = List.generate(_targetWord.length, (index) {
          if (input.length > index) {
            return Colors.black;
          } else {
            return Colors.grey;
          }
        });
      });
    }
  }

  void _showCompletionDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("完成复习"),
        content: const Text("恭喜！所有单词已通过两次正确拼写！"),
        actions: [
          TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text("确定")
          )
        ],
      ),
    );
  }

  void _showNoWordsDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("无需要复习的单词"),
        content: const Text("今天没有需要复习的单词，请继续学习新单词！"),
        actions: [
          TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text("确定")
          )
        ],
      ),
    );
  }

  void _clearInput() {
    setState(() {
      _textEditingController.clear();
      _wordColors = List.generate(_targetWord.length, (index) => Colors.grey);
    });
  }

  void _nextWord() {
    setState(() {
      _currentIndex = (_currentIndex + 1) % _currentList.length;
      _updateDisplayWord();
      _clearInput();
    });
  }

  // 删除_saveCompletionTime方法
  // 删除_checkCompletionStatus方法

  Widget _buildPhoneBody() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          if (_currentList.isEmpty)
            const Text(
              "已完成！",
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            )
          else ...[
            const SizedBox(),
            _ProgressIndicator(
              learnedCount: _totalInputCount,
              totalCount: _words.length * 2, // 总次数 = 单词数 * 2
            ),
          Column(
            children: [
              _Word(
                targetWord: _showHiddenWord ? _targetWord : _targetWord.replaceAllMapped(RegExp(r'[^ ]'), (match) => '*'),
                wordColors: _wordColors,
              ),
              _Translation(targetTranslation: _targetTranslation,),
              const SizedBox(height: 5,),
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.75,
                child: const PartingLine(),
              ),
              const SizedBox(height: 5,),
              _Example(example: _example,),
              _ExampleTranslation(exampleTranslation: _exampleTranslation,),
              // 用户输入框
              _Input(
                textEditingController: _textEditingController,
                updateTypedWord: _updateTypedWord,
                targetWord: _targetWord,
              ),
              const SizedBox(height: 20,),
              if (_showNextButton) // 只有在输入有误时显示“下一个单词”按钮
                ElevatedButton(
                  onPressed: _nextWord,
                  child: const Text("下一个单词"),
                ),
            ],
          ),
          const SizedBox(),
          const SizedBox(),
        ],
        ],
      ),
    );
  }

  Widget _buildPadBody() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          if (_currentList.isEmpty)
            const Text(
              "已完成！",
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            )
          else ...[
            _ProgressIndicator(
              learnedCount: _totalInputCount,
              totalCount: _words.length * 2, // 总次数 = 单词数 * 2
            ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              const SizedBox(width: 20,),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _Word(
                    targetWord: _showHiddenWord ? _targetWord : _targetWord.replaceAllMapped(RegExp(r'[^ ]'), (match) => '*'),
                    wordColors: _wordColors,
                    fontSize: 65.0,
                  ),
                  _Translation(targetTranslation: _targetTranslation,),
                ],
              ),
              const SizedBox(
                width: 1,
                height: 100,
                child: DecoratedBox(
                  decoration: BoxDecoration(color: Colors.grey),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  _Example(example: _example, fontSize: 23,),
                  _ExampleTranslation(exampleTranslation: _exampleTranslation, fontSize: 20,),
                ],
              ),
              const SizedBox(width: 20,),
            ],
          ),
          // 用户输入框
          SizedBox(
            width: 700,
            child: _Input(
              textEditingController: _textEditingController,
              updateTypedWord: _updateTypedWord,
              targetWord: _targetWord,
            ),
          ),
          const SizedBox(height: 20,),
          if (_showNextButton) // 只有在输入有误时显示“下一个单词”按钮
            ElevatedButton(
              onPressed: _nextWord,
              child: const Text("下一个单词"),
            ),
        ],
        ],
      ),
    );
  }

  Widget _buildBody() {
    final bool isMobileLayout = MediaQuery.of(context).size.width < 600;
    return isMobileLayout ? _buildPhoneBody() : _buildPadBody();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("单词抽查")),
      floatingActionButton: FloatingActionButton(
        onPressed: _clearInput,
        foregroundColor: Theme.of(context).colorScheme.background,
        child: const Icon(Icons.delete_forever),
      ),
      body: _buildBody(),
    );
  }
}

// 修改进度指示器组件
class _ProgressIndicator extends StatelessWidget {
  const _ProgressIndicator({
    required this.learnedCount,
    required this.totalCount,
  });

  final int learnedCount;
  final int totalCount;

  @override
  Widget build(BuildContext context) {
    // 检查分母是否为0，避免Infinity或NaN
    double progress = totalCount == 0 ? 0.0 : learnedCount / totalCount;
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
          child: ClipRRect(
            borderRadius: const BorderRadius.all(Radius.circular(10.0)),
            child: LinearProgressIndicator(
              minHeight: 5, // 增加高度
              backgroundColor: Colors.grey[200], // 更明显的背景色
              color: Theme.of(context).primaryColor, // 使用主题主色
              value: progress, // 使用计算后的进度值
            ),
          ),
        ),
        const SizedBox(height: 5),
        Text(
          '复习进度：${(progress * 100).toStringAsFixed(2)}%',
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }
}

class _Word extends StatefulWidget {
  const _Word({super.key, this.targetWord = "Error", required this.wordColors, this.fontSize = 48.0,});

  final String targetWord;
  final List<Color> wordColors;
  final double fontSize;

  @override
  State<_Word> createState() => _WordState();
}

class _WordState extends State<_Word> {
  @override
  Widget build(BuildContext context) {
    // 处理空字符串的情况
    if (widget.targetWord.isEmpty) {
      return const Text(
        "No word to display",
        style: TextStyle(
            color: Colors.grey,
            fontSize: 48.0,
            fontWeight: FontWeight.w600
        ),
      );
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(widget.targetWord.length, (index){
        return Text(
          widget.targetWord[index],
          style: TextStyle(
              color: widget.wordColors[index],
              fontSize: widget.fontSize,
              fontWeight: FontWeight.w600
          ),
        );
      },),
    );
  }
}

class _Translation extends StatefulWidget {
  const _Translation({super.key, this.targetTranslation = "错误"});

  final String targetTranslation;

  @override
  State<_Translation> createState() => _TranslationState();
}

class _TranslationState extends State<_Translation> {
  @override
  Widget build(BuildContext context) {
    return Text(
        widget.targetTranslation,
        style: const TextStyle(
            fontSize: 25.0,
            fontWeight: FontWeight.w500
        )
    );
  }
}

class _Example extends StatefulWidget {
  const _Example({super.key, this.example = "an error has occurred", this.fontSize = 17.0});

  final String example;
  final double fontSize;

  @override
  State<_Example> createState() => _ExampleState();
}

class _ExampleState extends State<_Example> {
  @override
  Widget build(BuildContext context) {
    return Text(
        widget.example,
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: widget.fontSize,
            fontWeight: FontWeight.w400
        )
    );
  }
}

class _ExampleTranslation extends StatefulWidget {
  const _ExampleTranslation({super.key, this.exampleTranslation = "错误示例翻译", this.fontSize = 17.0,});

  final String exampleTranslation;
  final double fontSize;

  @override
  State<_ExampleTranslation> createState() => _ExampleTranslationState();
}

// 其他UI组件保持不变
class _ExampleTranslationState extends State<_ExampleTranslation> {
  @override
  Widget build(BuildContext context) {
    return Text(
        widget.exampleTranslation,
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: widget.fontSize,
            fontWeight: FontWeight.w400
        )
    );
  }
}

class _Input extends StatefulWidget {
  const _Input({super.key, required this.textEditingController, required this.updateTypedWord, required this.targetWord});

  final TextEditingController textEditingController;
  final Function(String) updateTypedWord;
  final String targetWord;

  @override
  State<_Input> createState() => _InputState();
}

class _InputState extends State<_Input> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(50, 20, 50, 0),
      child: TextField(
        controller: widget.textEditingController,
        textAlign: TextAlign.center,
        onChanged: widget.updateTypedWord,
        maxLength: widget.targetWord.length,
        decoration: const InputDecoration(
          enabledBorder: OutlineInputBorder(),
          border: OutlineInputBorder(),
          hintText: '请在这里输入',
        ),
      ),
    );
  }
}
